package org.example.demo1.filter;


import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.demo1.Entity.User;

import java.awt.*;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;

@WebFilter(urlPatterns = "/MainPage/*", dispatcherTypes = {DispatcherType.REQUEST})
public class EncodingFilter implements Filter {

    private String encoding = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String configEncoding = filterConfig.getInitParameter("encoding");
        if (configEncoding != null) {
            encoding = configEncoding;
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("EncodingFilter doFilter");

        HttpServletRequest req = (HttpServletRequest) request;

        HttpServletResponse res = (HttpServletResponse) response;
        // 获取 Session（不创建新的）
        HttpSession session = req.getSession();
        User user= (User) session.getAttribute("user");
        System.out.println(session.getAttribute("user"));
        if(session.getAttribute("user")==null){
            res.sendRedirect(req.getContextPath() + "/login.jsp?errorCode=1");
            return;
        }else{
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {
        // 清理操作
    }
}
